package com.copa.module.user.manage.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import com.copa.config.WechatConfig;
import com.copa.domain.ResponseDto;
import com.copa.module.user.domain.entity.RoleEntity;
import com.copa.module.user.domain.entity.UserEntity;
import com.copa.module.user.manage.UserRoleManage;
import com.copa.module.user.mapper.RoleDao;
import com.copa.module.user.mapper.UserDao;
import com.google.gson.JsonParser;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.spring.web.json.Json;

import java.io.IOException;
import java.util.List;

/**
 * @author copa
 * @createDate 2021-01-05 14:09
 * @function
 */
@Service
public class UserRoleManageImpl implements UserRoleManage {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserDao userDao;

    @Override
    public ResponseDto<List<Long>> listRoleByUserIdAndRoleId(Long userId, Long roleId) {
        List<Long> roldIds = roleDao.listRoleByUserIdAndRoleId(userId, roleId);
        if (ObjectUtil.isNotNull(roldIds) && ObjectUtil.length(roldIds) > 0) {
            return ResponseDto.success(roldIds);
        }
        return ResponseDto.errorMsg("抱歉，该用户没有权限！");
    }

    @Override
    public ResponseDto<String> getOpenId(String code) {
        // https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/login/auth.code2Session.html
        try {
            Connection.Response response = Jsoup.connect("https://api.weixin.qq.com/sns/jscode2session?appid=" + WechatConfig.APP_ID + "&secret=" + WechatConfig.APP_SECRET + "&js_code="+ code +"&grant_type=authorization_code")
                    .method(Connection.Method.GET)
                    .execute();
            String json = response.body();
            String result = new JsonParser().parse(json).getAsJsonObject().get("openid").getAsString();
            return ResponseDto.success(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseDto.errorMsg("系统繁忙，请稍后再试！");
    }

    @Override
    public ResponseDto<String> addUserRole(UserEntity user) {
        Boolean flag = roleDao.insertUserRole(user);
        if (flag) {
            return ResponseDto.success();
        }
        return ResponseDto.errorMsg("系统繁忙，请稍后再试");
    }

    @Override
    public ResponseDto<UserEntity> getUserByOpenId(String openId) {
        UserEntity user = userDao.getUserByOpenId(openId);
        if (ObjectUtil.isNotNull(user)) {
            return ResponseDto.success(user);
        }
        return ResponseDto.errorMsg("没有查到所查用户的信息！");
    }
}
